<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="上一篇详细介绍了 SmoothBursty 的实现原理，本文将介绍带有预热机制的限速器实现原理。 1、类图从上文也详细介绍了 RateLimiter 相关的类图，本文就不详细介绍。 2、SmoothWarmingUp 创建流程创建 SmoothWarmingUp 限速器的入口为 RateLimiter 的 create 方法，其代码如下：RateLimiter#create 12345public">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图)">
<meta property="og:url" content="https://www.codingw.net/posts/6c0cb4a9.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="上一篇详细介绍了 SmoothBursty 的实现原理，本文将介绍带有预热机制的限速器实现原理。 1、类图从上文也详细介绍了 RateLimiter 相关的类图，本文就不详细介绍。 2、SmoothWarmingUp 创建流程创建 SmoothWarmingUp 限速器的入口为 RateLimiter 的 create 方法，其代码如下：RateLimiter#create 12345public">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200329155128855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200329155338150.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200329155751536.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2020-12-18T14:53:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:11:20.014Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200329155128855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/6c0cb4a9.html"/>





  <title>源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/6c0cb4a9.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-18T22:53:35+08:00">
                2020-12-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/6c0cb4a9.html" class="leancloud_visitors" data-flag-title="源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>上一篇详细介绍了 <a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/105027563">SmoothBursty</a> 的实现原理，本文将介绍带有预热机制的限速器实现原理。</p>
<h2 id="1、类图"><a href="#1、类图" class="headerlink" title="1、类图"></a>1、类图</h2><p><img src="https://img-blog.csdnimg.cn/20200329155128855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>从上文也详细介绍了 RateLimiter 相关的类图，本文就不详细介绍。</p>
<h2 id="2、SmoothWarmingUp-创建流程"><a href="#2、SmoothWarmingUp-创建流程" class="headerlink" title="2、SmoothWarmingUp 创建流程"></a>2、SmoothWarmingUp 创建流程</h2><p>创建 SmoothWarmingUp 限速器的入口为 RateLimiter 的 create 方法，其代码如下：<br>RateLimiter#create</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RateLimiter <span class="title">create</span><span class="params">(<span class="keyword">double</span> permitsPerSecond, <span class="keyword">long</span> warmupPeriod, TimeUnit unit)</span> </span>&#123;  <span class="comment">// @1</span></span><br><span class="line">    checkArgument(warmupPeriod &gt;= <span class="number">0</span>, <span class="string">&quot;warmupPeriod must not be negative: %s&quot;</span>, warmupPeriod);</span><br><span class="line">    <span class="keyword">return</span> create(</span><br><span class="line">        SleepingStopwatch.createFromSystemTimer(), permitsPerSecond, warmupPeriod, unit, <span class="number">3.0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先先来看一下参数列表：</p>
<ul>
<li>double permitsPerSecond<br>每秒发放许可数量，即所谓的QPS。</li>
<li>long warmupPeriod<br>设置预热时间。</li>
<li>TimeUnit unit<br>warmupPeriod 的时间单位。</li>
</ul>
<p>代码@2：调用内部的重载方法创建 SmoothWarmingUp 。</p>
<span id="more"></span>

<p>RateLimiter#create</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> RateLimiter <span class="title">create</span><span class="params">( SleepingStopwatch stopwatch, <span class="keyword">double</span> permitsPerSecond, <span class="keyword">long</span> warmupPeriod, TimeUnit unit, <span class="keyword">double</span> coldFactor)</span> </span>&#123;</span><br><span class="line">    RateLimiter rateLimiter = <span class="keyword">new</span> SmoothWarmingUp(stopwatch, warmupPeriod, unit, coldFactor);  <span class="comment">// @1</span></span><br><span class="line">    rateLimiter.setRate(permitsPerSecond); <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">return</span> rateLimiter;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>创建 SmoothWarmingUp 两个主要步骤分别是调用其构造方法首先创建 SmoothWarmingUp 实例，然后调用其 setRate 方法进行初始化速率。这里先突出 coldFactor，默认为 3.0，该属性的作用将在下文详细介绍。</p>
<p>我们先来重点探讨一下 setRate 方法的实现。最终会调用其父类 SmoothRateLimiter 的doSetRate 方法。</p>
<p>SmoothRateLimiter#doSetRate</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">doSetRate</span><span class="params">(<span class="keyword">double</span> permitsPerSecond, <span class="keyword">long</span> nowMicros)</span> </span>&#123;</span><br><span class="line">    resync(nowMicros);   <span class="comment">// @1 </span></span><br><span class="line">    <span class="keyword">double</span> stableIntervalMicros = SECONDS.toMicros(<span class="number">1L</span>) / permitsPerSecond;   </span><br><span class="line">    <span class="keyword">this</span>.stableIntervalMicros = stableIntervalMicros;   <span class="comment">// @2</span></span><br><span class="line">    doSetRate(permitsPerSecond, stableIntervalMicros);  <span class="comment">// @3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：基于当前时间重置 SmoothRateLimiter 内部的 storedPermits(已存储的许可数量) 与 nextFreeTicketMicros(下一次可以免费获取许可的时间) 值，所谓的免费指的是无需等待就可以获取设定速率的许可，该方法对理解限流许可的产生非常关键，稍后详细介绍。</p>
<p>代码@2：根据QPS算出一个稳定的获取1个许可的时间。以一秒发放5个许可，即限速为5QPS，那发放一个许可的世界间隔为 200ms，stableIntervalMicros 变量是以微妙为单位。</p>
<p>代码@4：调用 SmoothRateLimiter 的抽象方法 doSetRate 设置速率，这里会调用 SmoothWarmingUp 的 doSetRate 方法。</p>
<p>在介绍 SmoothWarmingUp 的 doSetRate 方法之前，我们先来看一下 resync 方法的实现。</p>
<p>SmoothRateLimiter#resync</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">resync</span><span class="params">(<span class="keyword">long</span> nowMicros)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (nowMicros &gt; nextFreeTicketMicros) &#123;  <span class="comment">// @1 </span></span><br><span class="line">      <span class="keyword">double</span> newPermits = (nowMicros - nextFreeTicketMicros) / coolDownIntervalMicros();  <span class="comment">// @2</span></span><br><span class="line">      storedPermits = min(maxPermits, storedPermits + newPermits);    <span class="comment">// @3</span></span><br><span class="line">      nextFreeTicketMicros = nowMicros;   <span class="comment">// @4</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果当前已启动时间大于nextFreeTicketMicros（下一次可以免费获取许可的时间），则需要重新计算许可，即又可以向许可池中添加许可。</p>
<p>代码@2：根据当前时间可增加的许可数量，由于 SmoothWarmingUp 实现了预热机制，平均生成一个许可的时间并不是固定不变的。具体由 coolDownIntervalMicros 方法实现，稍候详细介绍。</p>
<p>代码@3：计算当前可用的许可，将新增的这些许可添加到许可池，但不会超过其最大值。</p>
<p>代码@4：更新下一次可增加计算许可的时间。 </p>
<p>SmoothWarmingUp#coolDownIntervalMicros</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">double</span> <span class="title">coolDownIntervalMicros</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> warmupPeriodMicros / maxPermits;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个方法的实现其实简单，用生成这些许可的总时间除以现在已经生成的许可数，即可得到当前时间点平均一个许可的生成时间。</p>
<ol>
<li><p>接下来重点探讨 SmoothWarmingUp 的 doSetRate 方法。<br>为了方便理解 SmoothWarmingUp doSetRate 方法，我根据 SmoothWarmingUp 类的注释，结合代码，给出如下示例图：<br><img src="https://img-blog.csdnimg.cn/20200329155338150.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>首先我们先来根据 SmoothWarmingUp 的相关注释来理解一下上述这张图的几个要点。</p>
<ul>
<li>图中有两个阴影面积，一个用 stable，另外一个warm up period。在预热算法中，这两个阴影面积的关系与冷却因子相关。</li>
<li>冷却因子 coldFactor 表示的含义为 coldIntervalMicros 与  stableIntervalMicros 的比值。</li>
<li>warm up period 阴影面积 与 stable 阴影面积的比值等于 (coldIntervalMicros -  stableIntervalMicros ) / stableIntervalMicros ，例如 SmoothWarmingUp 固定的冷却因子为3，那么 coldIntervalMicros 与 stableIntervalMicros 的比值为 3，那  (coldIntervalMicros -  stableIntervalMicros ) / stableIntervalMicros 则为 2。</li>
<li>在预热算法中与数学中的积分相关（笔者对这方面的数学知识一窍不通），故这里只展示结论，而不做推导，阴影 WARM UP PERIOD 的面积等于 warmupPeriod,那阴影stable的面积等于 warmupPeriod/2。</li>
<li>存在如下等式 warmupPeriod/2 = thresholdPermits * stableIntervalMicros (长方形的面积)</li>
<li>同样存在如下等式 warmupPeriod = 0.5 * (stableInterval + coldInterval) * (maxPermits - thresholdPermits) （梯形面积，(上底 + 下底 * 高 / 2) ）</li>
</ul>
<p>有了上述基本知识，我们再来看一下代码。</p>
<p>SmoothWarmingUp#doSetRate</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">doSetRate</span><span class="params">(<span class="keyword">double</span> permitsPerSecond, <span class="keyword">double</span> stableIntervalMicros)</span> </span>&#123; </span><br><span class="line">    <span class="keyword">double</span> oldMaxPermits = maxPermits;</span><br><span class="line">    <span class="keyword">double</span> coldIntervalMicros = stableIntervalMicros * coldFactor;                <span class="comment">// @1</span></span><br><span class="line">    thresholdPermits = <span class="number">0.5</span> * warmupPeriodMicros / stableIntervalMicros;    <span class="comment">// @2</span></span><br><span class="line">    maxPermits =</span><br><span class="line">          thresholdPermits + <span class="number">2.0</span> * warmupPeriodMicros / (stableIntervalMicros + coldIntervalMicros);   <span class="comment">// @3</span></span><br><span class="line">    slope = (coldIntervalMicros - stableIntervalMicros) / (maxPermits - thresholdPermits);  <span class="comment">// @4</span></span><br><span class="line">    <span class="keyword">if</span> (oldMaxPermits == Double.POSITIVE_INFINITY) &#123;</span><br><span class="line">        storedPermits = <span class="number">0.0</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        storedPermits =</span><br><span class="line">            (oldMaxPermits == <span class="number">0.0</span>)</span><br><span class="line">                ? maxPermits <span class="comment">// initial state is cold</span></span><br><span class="line">                : storedPermits * maxPermits / oldMaxPermits;    <span class="comment">// @5</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据冷却因子(coldFactor)来计算冷却间隔(单位为微秒)，等于冷却因子与 stableIntervalMicros 的乘积。从这里我们可以得出如下几个基本的概念。冷却因子 coldFactor 为 冷却间隔与稳定间隔的比例。</p>
<p>代码@2：通过  warmupPeriod/2 = thresholdPermits * stableIntervalMicros 等式，求出 thresholdPermits 的值。</p>
<p>代码@3：根据  warmupPeriod = 0.5 * (stableInterval + coldInterval) * (maxPermits - thresholdPermits)  表示可求出 maxPermits 的数量。</p>
<p>代码@4：斜率，表示的是从 stableIntervalMicros 到 coldIntervalMicros 这段时间，许可数量从 thresholdPermits 变为 maxPermits 的增长速率。</p>
<p>代码@5：根据 maxPermits 更新当前存储的许可，即当前剩余可消耗的许可数量。</p>
<h2 id="3、SmoothWarmingUp-acquire-流程"><a href="#3、SmoothWarmingUp-acquire-流程" class="headerlink" title="3、SmoothWarmingUp acquire 流程"></a>3、SmoothWarmingUp acquire 流程</h2><p>首先 acquire 的定义在其父类，这里是典型的模板模式，由其父类定义基本流程，由具体的子类实现其特定功能。RateLimiter 中的 acquire 方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">acquire</span><span class="params">(<span class="keyword">int</span> permits)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> microsToWait = reserve(permits);    <span class="comment">// @1</span></span><br><span class="line">    stopwatch.sleepMicrosUninterruptibly(microsToWait);   <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1.0</span> * microsToWait / SECONDS.toMicros(<span class="number">1L</span>);   <span class="comment">// @3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据当前剩余的许可与本次申请的许可来判断本次申请需要等待的时长，如果返回0则表示无需等待。</p>
<p>代码@2：如果需要等待的时间不为0，表示触发限速，睡眠指定时间后唤醒。</p>
<p>代码@3：返回本次申请等待的时长。</p>
<p>接下来重点介绍 reserve 方法的实现原理。</p>
<p>RateLimiter#reserve</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">inal <span class="keyword">long</span> <span class="title">reserve</span><span class="params">(<span class="keyword">int</span> permits)</span> </span>&#123;</span><br><span class="line">    checkPermits(permits);</span><br><span class="line">    <span class="keyword">synchronized</span> (mutex()) &#123;  <span class="comment">// @1</span></span><br><span class="line">      <span class="keyword">return</span> reserveAndGetWaitLength(permits, stopwatch.readMicros()); <span class="comment">// @2</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：限速器主要维护的重要数据字段(storedPermits)，对其进行维护时都需要先获取锁。</p>
<p>代码@2：调用内部方法 reserveAndGetWaitLength 来计算需要等待时间。</p>
<p>继续跟踪 reserveAndGetWaitLength 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">long</span> <span class="title">reserveAndGetWaitLength</span><span class="params">(<span class="keyword">int</span> permits, <span class="keyword">long</span> nowMicros)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> momentAvailable = reserveEarliestAvailable(permits, nowMicros);   <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">return</span> max(momentAvailable - nowMicros, <span class="number">0</span>);  <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据当前拥有的许可数量、当前时间判断待申请许可最早能得到满足的最早时间，用momentAvailable 表示。</p>
<p>代码@2：然后计算 momentAvailable 与 nowMicros 的差值与0做比较，得出需要等待的时间。</p>
<p>继续跟踪 reserveEarliestAvailable方法，该方法在 RateLimiter 中一个抽象方法，具体实现在其子类 SmoothRateLimiter 中。</p>
<p>SmoothRateLimiter#reserveEarliestAvailable</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">long</span> <span class="title">reserveEarliestAvailable</span><span class="params">(<span class="keyword">int</span> requiredPermits, <span class="keyword">long</span> nowMicros)</span> </span>&#123;</span><br><span class="line">    resync(nowMicros);   <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">long</span> returnValue = nextFreeTicketMicros;</span><br><span class="line">    <span class="keyword">double</span> storedPermitsToSpend = min(requiredPermits, <span class="keyword">this</span>.storedPermits); <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">double</span> freshPermits = requiredPermits - storedPermitsToSpend; <span class="comment">// @3</span></span><br><span class="line">    <span class="keyword">long</span> waitMicros =</span><br><span class="line">        storedPermitsToWaitTime(<span class="keyword">this</span>.storedPermits, storedPermitsToSpend)</span><br><span class="line">            + (<span class="keyword">long</span>) (freshPermits * stableIntervalMicros);  <span class="comment">// @4</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.nextFreeTicketMicros = LongMath.saturatedAdd(nextFreeTicketMicros, waitMicros);  <span class="comment">// @5</span></span><br><span class="line">    <span class="keyword">this</span>.storedPermits -= storedPermitsToSpend;    <span class="comment">// @6</span></span><br><span class="line">    <span class="keyword">return</span> returnValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：在尝试申请许可之前，先根据当前时间即发放许可速率更新 storedPermits 与 nextFreeTicketMicros（下一次可以免费获取许可的时间）。</p>
<p>代码@2：计算本次能从 storedPermits 中消耗的许可数量，取需要申请的许可数量与当前可用的许可数量的最小值，用 storedPermitsToSpend 表示。</p>
<p>代码@3：如果需要申请的许可数量(requiredPermits)大于当前剩余许可数量(storedPermits)，则还需要等待新的许可生成，用freshPermits 表示，即如果该值大于0，则表示本次申请需要阻塞一定时间。</p>
<p>代码@4：计算本次申请需要等待的时间，等待的时间由两部分组成，一部分是由 storedPermitsToWaitTime 方法返回的，另外一部分以稳定速率生成需要的许可，其需要时间为 freshPermits * stableIntervalMicros,稍后我们详细分析一下 storedPermitsToWaitTime 方法的实现。</p>
<p>代码@5：更新 nextFreeTicketMicros 为当前时间加上需要等待的时间。</p>
<p>代码@6：更新 storedPermits 的值，即减少本次已消耗的许可数量。</p>
<p>代码@7：请注意这里返回的 returnValue 的值，并没有包含由于剩余许可需要等待创建新许可的时间，即允许一定的突发流量，故本次计算需要的等待时间将对下一次请求生效。</p>
<p>接下来重点探讨一下 SmoothWarmingUp 的 storedPermitsToWaitTime 方法。</p>
<p>SmoothWarmingUp#SmoothWarmingUp </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">long</span> <span class="title">storedPermitsToWaitTime</span><span class="params">(<span class="keyword">double</span> storedPermits, <span class="keyword">double</span> permitsToTake)</span> </span>&#123;  <span class="comment">// @1</span></span><br><span class="line">	<span class="keyword">double</span> availablePermitsAboveThreshold = storedPermits - thresholdPermits;   <span class="comment">// @2</span></span><br><span class="line">	<span class="keyword">long</span> micros = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span> (availablePermitsAboveThreshold &gt; <span class="number">0.0</span>) &#123;  <span class="comment">// @3</span></span><br><span class="line">		<span class="keyword">double</span> permitsAboveThresholdToTake = min(availablePermitsAboveThreshold, permitsToTake);  <span class="comment">// @31 </span></span><br><span class="line">                <span class="comment">// TODO(cpovirk): Figure out a good name for this variable.</span></span><br><span class="line">                <span class="keyword">double</span> length = permitsToTime(availablePermitsAboveThreshold)</span><br><span class="line">                     + permitsToTime(availablePermitsAboveThreshold - permitsAboveThresholdToTake);             <span class="comment">// @32</span></span><br><span class="line">                micros = (<span class="keyword">long</span>) (permitsAboveThresholdToTake * length / <span class="number">2.0</span>);                                                      <span class="comment">// @33</span></span><br><span class="line">                permitsToTake -= permitsAboveThresholdToTake;                                                                          <span class="comment">// @34</span></span><br><span class="line">         &#125;</span><br><span class="line">        <span class="comment">// measuring the integral on the left part of the function (the horizontal line)</span></span><br><span class="line">        micros += (stableIntervalMicros * permitsToTake);   <span class="comment">// @4</span></span><br><span class="line">        <span class="keyword">return</span> micros;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先介绍其两个参数的含义：</p>
<ul>
<li>double storedPermits<br>当前存储的许可数量。</li>
<li>double permitsToTake<br>本次申请需要的许可数量。</li>
</ul>
<p>代码@2：availablePermitsAboveThreshold ，当前超出 thresholdPermits 的许可个数，如果超过 thresholdPermits ，申请许可将来源于超过的部分，只有其不足后，才会从 thresholdPermits 中申请，这部分的详细逻辑见代码@3。</p>
<p>代码@3：如果当前存储的许可数量超过了稳定许可 thresholdPermits，即存在预热的许可数量的申请逻辑，其实现关键点如下：</p>
<ul>
<li>获取本次从预热区间申请的许可数量。</li>
<li>从预热区间获取一个许可的时间其算法有点晦涩难懂，具体实现为@32~@34。</li>
</ul>
<p>代码@4：从稳定区间获取一个许可的时间，就容易理解，为固定的 stableIntervalMicros 。</p>
<blockquote>
<p>温馨提示：从预热区间计算获取多个许可的算法，与 slope 有关，笔者并未完成感悟，但至少我们需要明白的是，从 剩余许可(storedPermits)中申请许可时，优先消耗(大于thresholdPermits 的许可，即消耗 (thresholdPermits ~ maxPermit ) 之间的许可)。</p>
</blockquote>
<p>SmoothWarmingUp 的 acquire 流程就介绍到这里了。</p>
<h2 id="4、总结"><a href="#4、总结" class="headerlink" title="4、总结"></a>4、总结</h2><p>SmoothWarmingUp 的 acquire 的流程与 SmoothBursty 类似，故其流程图与下图通用，主要的区别生成一个许可的时间有变化，主要是提供了预热机制。<br><img src="https://img-blog.csdnimg.cn/20200329155751536.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</li>
</ol>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/a6ee7996.html" rel="next" title="源码分析RocketMQ ACL实现机制">
                <i class="fa fa-chevron-left"></i> 源码分析RocketMQ ACL实现机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/be152999.html" rel="prev" title="Netty4 事件处理传播机制">
                Netty4 事件处理传播机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E7%B1%BB%E5%9B%BE"><span class="nav-number">1.</span> <span class="nav-text">1、类图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81SmoothWarmingUp-%E5%88%9B%E5%BB%BA%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2、SmoothWarmingUp 创建流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81SmoothWarmingUp-acquire-%E6%B5%81%E7%A8%8B"><span class="nav-number">3.</span> <span class="nav-text">3、SmoothWarmingUp acquire 流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81%E6%80%BB%E7%BB%93"><span class="nav-number">4.</span> <span class="nav-text">4、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
